package com.pactera.madp.cp.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.cp.api.dto.moment.MomentDetailsTendencyDTO;
import com.pactera.madp.cp.api.dto.moment.MomentDto;
import com.pactera.madp.cp.api.dto.moment.MomentTask;
import com.pactera.madp.cp.api.dto.moment.WxMomentDto;
import com.pactera.madp.cp.api.entity.WorkDeptEntity;
import com.pactera.madp.cp.api.entity.WorkEmployeeEntity;
import com.pactera.madp.cp.api.feign.RemoteDeptService;
import com.pactera.madp.cp.api.vo.moment.InteractionVo;
import com.pactera.madp.cp.api.vo.moment.MomentStaticsTendencyVO;
import com.pactera.madp.cp.api.vo.moment.MomentStatisticsDataVO;
import com.pactera.madp.cp.api.vo.moment.MomentVo;
import com.pactera.madp.cp.common.util.PageUtil;
import com.pactera.madp.cp.common.util.WxApiUtils;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.service.IWorkDeptService;
import com.pactera.madp.cp.service.IWorkEmployeeService;
import com.pactera.madp.cp.service.MomentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

import static com.pactera.madp.cp.common.util.DateHastListUtil.getDetHashList;

@Service
@Slf4j
public class MomentServiceImpl implements MomentService {

    @Autowired
    private IWorkEmployeeService workEmployeeService;
    @Autowired
    private IWorkEmployeeService employeeService;
    @Autowired
    private IWorkDeptService deptService;
    @Autowired
    private RemoteDeptService remoteDeptService;

    @Override
    public Page<MomentVo> selectByCondition(Integer pageNumber, Integer pageSize, MomentDto dto) {
        Integer corpId = CorpContextHolder.getCorpId();
        String allMoments = WxApiUtils.getMoment(corpId);
        JSONArray allMomentArr = JSONArray.parseArray(allMoments);
        ArrayList<MomentVo> vos = new ArrayList<>();
        List<MomentVo> list = transform(corpId, allMomentArr);
        List<MomentVo> ress = new ArrayList<>();
        ress.addAll(list);
        list.forEach(f -> {
            if (dto.getWxEmployeeId() != null && !dto.getWxEmployeeId().equals("")) if (!f.getWxEmployeeId().contains(dto.getWxEmployeeId())) ress.remove(f);

            if (dto.getEmployeeName() != null && !dto.getEmployeeName().equals("")) if (!f.getEmployeeName().contains(dto.getEmployeeName())) ress.remove(f);

            if (dto.getCreateType() != null) if (!f.getCreateType().equals(dto.getCreateType())) ress.remove(f);

            if (dto.getStartTime() != null && dto.getStartTime() != "") if (f.getCreateTime().compareTo(dto.getStartTime()) < 0)  ress.remove(f);

            if (dto.getEndTime() != null && dto.getEndTime() != "") if (f.getCreateTime().compareTo(dto.getEndTime()) > 0)  ress.remove(f);
        });
        ress.forEach(f -> {
            MomentVo vo = new MomentVo();
            BeanUtils.copyProperties(f, vo);
            String format = f.getCreateTime();
            vo.setCreateTime(format);
            vos.add(vo);
        });
        Collections.sort(list, new Comparator<MomentVo>() {
            @Override
            public int compare(MomentVo o1, MomentVo o2) {
                return o2.getCreateTime().compareTo(o1.getCreateTime());
            }
        });
        Page<MomentVo> split = PageUtil.split(vos, pageNumber, pageSize);
        return split;
    }

    @Override
    public Page<MomentTask> task(MomentDto dto, Page page) {
        String momentId = dto.getMomentId();
        ArrayList<MomentTask> momentTasks = new ArrayList<>();
        Integer corpId = CorpContextHolder.getCorpId();
        String taskJson = WxApiUtils.getMomentTask(corpId, momentId);
        JSONArray tasks = JSONArray.parseArray(taskJson);
        if (tasks == null) {
            page.setTotal(1);
            ArrayList<MomentTask> list = new ArrayList<>();
            MomentTask momentTask = new MomentTask();
            momentTask.setMomentId(momentId);
            momentTask.setPublishStatus(1);
            momentTask.setEmployeeName(dto.getEmployeeName());
            momentTask.setEmployeeId(dto.getWxEmployeeId());
            InteractionVo interaction = interaction(dto.getMomentId(), dto.getWxEmployeeId());
            momentTask.setLikes(interaction.getLikes());
            momentTask.setComments(interaction.getComments());
            list.add(momentTask);
            page.setTotal(1);
            page.setRecords(list);
            return page;
        }

        for (int i = 0; i < tasks.size(); i++) {
            MomentTask task = new MomentTask();
            task.setMomentId(momentId);
            Object publish_status = tasks.getJSONObject(i).get("publish_status");
            Object userid = tasks.getJSONObject(i).get("userid");
            QueryWrapper<WorkEmployeeEntity> wrapper = new QueryWrapper<>();
            wrapper.select("name").eq("wx_user_id", userid.toString());
            wrapper.eq("corp_id", corpId);
            String name = employeeService.getOne(wrapper).getName();
            task.setEmployeeName(name);
            task.setPublishStatus(Integer.parseInt(publish_status.toString()));
            task.setEmployeeId(userid.toString());
            InteractionVo interaction = new InteractionVo(0, 0);
            if (task.getPublishStatus().equals(1)) interaction = interaction(momentId, userid.toString());
            task.setComments(interaction.getComments());
            task.setLikes(interaction.getLikes());
            momentTasks.add(task);
        }
        Page<MomentTask> split = PageUtil.split(momentTasks, (int) page.getCurrent(), (int) page.getSize());
        return split;
    }

    @Override
    public List<MomentVo> getAllMomentVos() {
        Integer corpId = CorpContextHolder.getCorpId();
        String allMoments = WxApiUtils.getMoment(corpId);
        JSONArray allMomentArr = JSONArray.parseArray(allMoments);
        ArrayList<MomentVo> vos = new ArrayList<>();
        List<MomentVo> list = transform(corpId, allMomentArr);
        vos.addAll(list);
        return vos;
    }

    @Override
    public MomentStatisticsDataVO getStatisticsDatas(Integer deptId, Integer wxDeptId,List<MomentVo> allMomentVos) {
        MomentStatisticsDataVO vo;
        Set<Integer> employeeIds = getEmployees(deptId);
        if (employeeIds == null || employeeIds.size() == 0) {
            vo = new MomentStatisticsDataVO();
            vo.setMomentTotalCount(0);
            vo.setEnterpriseMomentCount(0);
            vo.setPersonalMomentCount(0);
            vo.setLikesCount(0);
            vo.setCommentsCount(0);
            vo.setEmployeeCount(0);
        } else {
            vo = getStatisticsData(employeeIds,allMomentVos);
        }
        WorkDeptEntity workDeptEntity = deptService.getOne(
                Wrappers.<WorkDeptEntity>lambdaQuery()
                        .eq(WorkDeptEntity::getWxDepartmentId, wxDeptId)
        );
        vo.setCode(String.valueOf(workDeptEntity.getWxDepartmentId()));
        vo.setName(workDeptEntity.getName());
        return vo;
    }

    @Override
    public MomentStatisticsDataVO getStatisticsDatas(String mobile,List<MomentVo> allMomentVos) {
        WorkEmployeeEntity entity = employeeService.getOne(
                Wrappers.<WorkEmployeeEntity>lambdaQuery()
                        .select(WorkEmployeeEntity::getId, WorkEmployeeEntity::getWxUserId, WorkEmployeeEntity::getName)
                        .eq(WorkEmployeeEntity::getMobile, mobile)
        );
        Set<Integer> employeeIds = new HashSet<>();
        employeeIds.add(entity.getId());
        MomentStatisticsDataVO vo = getStatisticsData(employeeIds,allMomentVos);
        vo.setCode(entity.getWxUserId());
        vo.setName(entity.getName());
        return vo;
    }

    @Override
    public List<MomentStaticsTendencyVO> getMomentTotalCount(MomentDetailsTendencyDTO dto) {
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        List<MomentStaticsTendencyVO> vos = new ArrayList<>();
        if (employeeIds.isEmpty()) {
            hashList.forEach(s -> {
                Integer momentTotalCount = 0;
                MomentStaticsTendencyVO vo = new MomentStaticsTendencyVO();
                vo.setTime(s.toDateStr());
                vo.setType(dto.getType());
                vo.setNumber(momentTotalCount);
                vos.add(vo);
            });
            return vos;
        } else {
            List<String> wxUserIds = employeeService.list(new LambdaQueryWrapper<WorkEmployeeEntity>()
                    .in(WorkEmployeeEntity::getId, employeeIds))
                    .stream()
                    .map(WorkEmployeeEntity::getWxUserId)
                    .collect(Collectors.toList());
            List<MomentVo> allMomentVosByDate = getAllMomentVosByDate(dto.getStartTime(), dto.getEndTime());

            //当前机构下的朋友圈列表(起止时间范围内的)
            List<MomentVo> momentVosByWxEmpIds = allMomentVosByDate.stream()
                    .filter(m -> wxUserIds.contains(m.getWxEmployeeId()))
                    .collect(Collectors.toList());
            hashList.forEach(s -> {
                Integer momentTotalCount = 0;
                List<MomentVo> momentVos = momentVosByWxEmpIds.stream()
                        .filter(m -> m.getCreateTime().equals(s.toDateStr()))
                        .collect(Collectors.toList());
                momentTotalCount = momentVos.size();
                MomentStaticsTendencyVO vo = new MomentStaticsTendencyVO();
                vo.setTime(s.toDateStr());
                vo.setType(dto.getType());
                vo.setNumber(momentTotalCount);
                vos.add(vo);
            });
            return vos;
        }
    }

    @Override
    public List<MomentStaticsTendencyVO> getEnterpriseMomentCount(MomentDetailsTendencyDTO dto) {
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        List<MomentStaticsTendencyVO> vos = new ArrayList<>();
        if (employeeIds.isEmpty()) {
            hashList.forEach(s -> {
                Integer enterpriseMomentCount = 0;
                MomentStaticsTendencyVO vo = new MomentStaticsTendencyVO();
                vo.setTime(s.toDateStr());
                vo.setType(dto.getType());
                vo.setNumber(enterpriseMomentCount);
                vos.add(vo);
            });
            return vos;
        } else {
            List<String> wxUserIds = employeeService.list(new LambdaQueryWrapper<WorkEmployeeEntity>()
                    .in(WorkEmployeeEntity::getId, employeeIds))
                    .stream()
                    .map(WorkEmployeeEntity::getWxUserId)
                    .collect(Collectors.toList());
            List<MomentVo> allMomentVosByDate = getAllMomentVosByDate(dto.getStartTime(), dto.getEndTime());

            //当前机构下的朋友圈列表(起止时间范围内的)
            List<MomentVo> momentVosByWxEmpIds = allMomentVosByDate.stream()
                    .filter(m -> wxUserIds.contains(m.getWxEmployeeId()))
                    .collect(Collectors.toList());
            hashList.forEach(s -> {
                Integer enterpriseMomentCount = 0;
                List<MomentVo> momentVos = momentVosByWxEmpIds.stream()
                        .filter(m -> m.getCreateTime().equals(s.toDateStr()) && m.getCreateType().equals(0))
                        .collect(Collectors.toList());
                enterpriseMomentCount = momentVos.size();
                MomentStaticsTendencyVO vo = new MomentStaticsTendencyVO();
                vo.setTime(s.toDateStr());
                vo.setType(dto.getType());
                vo.setNumber(enterpriseMomentCount);
                vos.add(vo);
            });
            return vos;
        }
    }

    @Override
    public List<MomentStaticsTendencyVO> getPersonalMomentCount(MomentDetailsTendencyDTO dto) {
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        List<MomentStaticsTendencyVO> vos = new ArrayList<>();
        if (employeeIds.isEmpty()) {
            hashList.forEach(s -> {
                Integer personalMomentCount = 0;
                MomentStaticsTendencyVO vo = new MomentStaticsTendencyVO();
                vo.setTime(s.toDateStr());
                vo.setType(dto.getType());
                vo.setNumber(personalMomentCount);
                vos.add(vo);
            });
            return vos;
        } else {
            List<String> wxUserIds = employeeService.list(new LambdaQueryWrapper<WorkEmployeeEntity>()
                    .in(WorkEmployeeEntity::getId, employeeIds))
                    .stream()
                    .map(WorkEmployeeEntity::getWxUserId)
                    .collect(Collectors.toList());
            List<MomentVo> allMomentVosByDate = getAllMomentVosByDate(dto.getStartTime(), dto.getEndTime());

            //当前机构下的朋友圈列表(起止时间范围内的)
            List<MomentVo> momentVosByWxEmpIds = allMomentVosByDate.stream()
                    .filter(m -> wxUserIds.contains(m.getWxEmployeeId()))
                    .collect(Collectors.toList());
            hashList.forEach(s -> {
                Integer personalMomentCount = 0;
                List<MomentVo> momentVos = momentVosByWxEmpIds.stream()
                        .filter(m -> m.getCreateTime().equals(s.toDateStr()) && m.getCreateType().equals(1))
                        .collect(Collectors.toList());
                personalMomentCount = momentVos.size();
                MomentStaticsTendencyVO vo = new MomentStaticsTendencyVO();
                vo.setTime(s.toDateStr());
                vo.setType(dto.getType());
                vo.setNumber(personalMomentCount);
                vos.add(vo);
            });
            return vos;
        }
    }

    @Override
    public List<MomentStaticsTendencyVO> getLikesCount(MomentDetailsTendencyDTO dto) {
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        List<MomentStaticsTendencyVO> vos = new ArrayList<>();
        if (employeeIds.isEmpty()) {
            hashList.forEach(s -> {
                Integer likesCount = 0;
                MomentStaticsTendencyVO vo = new MomentStaticsTendencyVO();
                vo.setTime(s.toDateStr());
                vo.setType(dto.getType());
                vo.setNumber(likesCount);
                vos.add(vo);
            });
            return vos;
        } else {
            List<String> wxUserIds = employeeService.list(new LambdaQueryWrapper<WorkEmployeeEntity>()
                    .in(WorkEmployeeEntity::getId, employeeIds))
                    .stream()
                    .map(WorkEmployeeEntity::getWxUserId)
                    .collect(Collectors.toList());
            List<MomentVo> allMomentVosByDate = getAllMomentVosByDate(dto.getStartTime(), dto.getEndTime());

            //当前机构下的朋友圈列表(起止时间范围内的)
            List<MomentVo> momentVosByWxEmpIds = allMomentVosByDate.stream()
                    .filter(m -> wxUserIds.contains(m.getWxEmployeeId()))
                    .collect(Collectors.toList());
            hashList.forEach(s -> {
                Integer likesCount = 0;
                List<MomentVo> momentVos = momentVosByWxEmpIds.stream()
                        .filter(m -> m.getCreateTime().equals(s.toDateStr()))
                        .collect(Collectors.toList());
                if (!momentVos.isEmpty()) {
                    for (MomentVo momentVo : momentVos) {
                        switch (momentVo.getCreateType()) {
                            case 0:
                                ArrayList<String> legalWxEmployeeIds = getLegalWxEmployeeIds(momentVo.getMomentId());
                                if (legalWxEmployeeIds.contains(momentVo.getWxEmployeeId())) {
                                    InteractionVo interactionVo = interaction(momentVo.getMomentId(), momentVo.getWxEmployeeId());
                                    likesCount += interactionVo.getLikes();
                                }
                                break;
                            case 1:
                                InteractionVo interactionVo = interaction(momentVo.getMomentId(), momentVo.getWxEmployeeId());
                                likesCount += interactionVo.getLikes();
                                break;
                            default:
                                throw new IllegalArgumentException("朋友圈类型不合法,0-企业,1-个人");
                        }
                    }
                }
                MomentStaticsTendencyVO vo = new MomentStaticsTendencyVO();
                vo.setTime(s.toDateStr());
                vo.setType(dto.getType());
                vo.setNumber(likesCount);
                vos.add(vo);
            });
            return vos;
        }
    }

    @Override
    public List<MomentStaticsTendencyVO> getCommentsCount(MomentDetailsTendencyDTO dto) {
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        List<MomentStaticsTendencyVO> vos = new ArrayList<>();
        if (employeeIds.isEmpty()) {
            hashList.forEach(s -> {
                Integer commentsCount = 0;
                MomentStaticsTendencyVO vo = new MomentStaticsTendencyVO();
                vo.setTime(s.toDateStr());
                vo.setType(dto.getType());
                vo.setNumber(commentsCount);
                vos.add(vo);
            });
            return vos;
        } else {
            List<String> wxUserIds = employeeService.list(new LambdaQueryWrapper<WorkEmployeeEntity>()
                    .in(WorkEmployeeEntity::getId, employeeIds))
                    .stream()
                    .map(WorkEmployeeEntity::getWxUserId)
                    .collect(Collectors.toList());
            List<MomentVo> allMomentVosByDate = getAllMomentVosByDate(dto.getStartTime(), dto.getEndTime());

            //当前机构下的朋友圈列表(起止时间范围内的)
            List<MomentVo> momentVosByWxEmpIds = allMomentVosByDate.stream()
                    .filter(m -> wxUserIds.contains(m.getWxEmployeeId()))
                    .collect(Collectors.toList());
            hashList.forEach(s -> {
                Integer commentsCount = 0;
                List<MomentVo> momentVos = momentVosByWxEmpIds.stream()
                        .filter(m -> m.getCreateTime().equals(s.toDateStr()))
                        .collect(Collectors.toList());
                if (!momentVos.isEmpty()) {
                    for (MomentVo momentVo : momentVos) {
                        switch (momentVo.getCreateType()) {
                            case 0:
                                ArrayList<String> legalWxEmployeeIds = getLegalWxEmployeeIds(momentVo.getMomentId());
                                if (legalWxEmployeeIds.contains(momentVo.getWxEmployeeId())) {
                                    InteractionVo interactionVo = interaction(momentVo.getMomentId(), momentVo.getWxEmployeeId());
                                    commentsCount += interactionVo.getComments();
                                }
                                break;
                            case 1:
                                InteractionVo interactionVo = interaction(momentVo.getMomentId(), momentVo.getWxEmployeeId());
                                commentsCount += interactionVo.getComments();
                                break;
                            default:
                                throw new IllegalArgumentException("朋友圈类型不合法,0-企业,1-个人");
                        }
                    }
                }
                MomentStaticsTendencyVO vo = new MomentStaticsTendencyVO();
                vo.setTime(s.toDateStr());
                vo.setType(dto.getType());
                vo.setNumber(commentsCount);
                vos.add(vo);
            });
            return vos;
        }
    }

    @Override
    public List<MomentStaticsTendencyVO> getEmployeeCount(MomentDetailsTendencyDTO dto) {
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        Integer corpId = CorpContextHolder.getCorpId();
        List<MomentStaticsTendencyVO> vos = new ArrayList<>();

        hashList.forEach(s -> {
            String end = s.toDateStr().substring(0, 10) + " 23:59:59";

            Integer empTotal = 0;
            if (employeeIds != null && employeeIds.size() != 0) {
                empTotal = workEmployeeService.count(
                        Wrappers.<WorkEmployeeEntity>lambdaQuery()
                                .eq(WorkEmployeeEntity::getCorpId, corpId)
                                .in(WorkEmployeeEntity::getId, employeeIds)
                                .lt(WorkEmployeeEntity::getCreateTime, end)
                );
            }

            MomentStaticsTendencyVO vo = new MomentStaticsTendencyVO();
            vo.setTime(s.toDateStr());
            vo.setType(dto.getType());
            vo.setNumber(empTotal);
            vos.add(vo);
        });
        return vos;
    }

    /**
     * 获取起止日期内的朋友圈列表
     * @param startTime
     * @param endTime
     * @return
     */
    private List<MomentVo> getAllMomentVosByDate(String startTime, String endTime) {
        Integer corpId = CorpContextHolder.getCorpId();
        String allMoments = WxApiUtils.getMomentByDate(corpId,startTime,endTime);
        JSONArray allMomentArr = JSONArray.parseArray(allMoments);
        ArrayList<MomentVo> vos = new ArrayList<>();
        List<MomentVo> list = transform(corpId, allMomentArr);
        vos.addAll(list);
        return vos;
    }

    private MomentStatisticsDataVO getStatisticsData(Set<Integer> employeeIds, List<MomentVo> allMomentVos) {
        List<String> wxUserIds = employeeService.list(new LambdaQueryWrapper<WorkEmployeeEntity>()
                .in(WorkEmployeeEntity::getId, employeeIds))
                .stream()
                .map(WorkEmployeeEntity::getWxUserId)
                .collect(Collectors.toList());
        //当前机构下的朋友圈
        List<MomentVo> momentVosByWxEmpIds = allMomentVos.stream()
                .filter(m -> wxUserIds.contains(m.getWxEmployeeId()))
                .collect(Collectors.toList());

        //朋友圈总数量
        Integer momentTotalCount = momentVosByWxEmpIds.size();
        //企业朋友圈数
        Integer enterpriseMomentCount = 0;
        //个人朋友圈数
        Integer personalMomentCount = 0;
        //点赞数
        Integer likesCount = 0;
        //评论数
        Integer commentsCount = 0;
        //成员数
        Integer employeeCount = workEmployeeService.count(
                Wrappers.<WorkEmployeeEntity>lambdaQuery()
                        .in(WorkEmployeeEntity::getId, employeeIds));

        if (!momentVosByWxEmpIds.isEmpty()) {
            for (MomentVo momentVosByWxEmpId : momentVosByWxEmpIds) {
                switch (momentVosByWxEmpId.getCreateType()) {
                    case 0:
                        enterpriseMomentCount += 1;
                        break;
                    case 1:
                        personalMomentCount += 1;
                        break;
                }
                switch (momentVosByWxEmpId.getCreateType()) {
                    case 0:
                        ArrayList<String> legalWxEmployeeIds = getLegalWxEmployeeIds(momentVosByWxEmpId.getMomentId());
                        if (legalWxEmployeeIds.contains(momentVosByWxEmpId.getWxEmployeeId())) {
                            InteractionVo interactionVo = interaction(momentVosByWxEmpId.getMomentId(), momentVosByWxEmpId.getWxEmployeeId());
                            likesCount += interactionVo.getLikes();
                            commentsCount += interactionVo.getComments();
                        }
                        break;
                    case 1:
                        InteractionVo interactionVo = interaction(momentVosByWxEmpId.getMomentId(), momentVosByWxEmpId.getWxEmployeeId());
                        likesCount += interactionVo.getLikes();
                        commentsCount += interactionVo.getComments();
                        break;
                    default:
                        throw new IllegalArgumentException("朋友圈类型不合法,0-企业,1-个人");
                }
            }
        }

        MomentStatisticsDataVO vo = new MomentStatisticsDataVO();
        vo.setMomentTotalCount(momentTotalCount);
        vo.setEnterpriseMomentCount(enterpriseMomentCount);
        vo.setPersonalMomentCount(personalMomentCount);
        vo.setLikesCount(likesCount);
        vo.setCommentsCount(commentsCount);
        vo.setEmployeeCount(employeeCount);
        return vo;
    }



    private Set<Integer> getEmployees(Integer deptId) {
        R r = remoteDeptService.getDeptsAndUsers(deptId);
        log.info("r:{}",r);
        Map<String, Object> data = (Map) r.getData();
        List<Integer> wxDeptIds = (List<Integer>) data.get("wxDeptIds");
        List<String> userMobiles = (List<String>) data.get("userMobiles");
        return employeeService.getEmployeeIds(wxDeptIds, userMobiles);
    }

    List<MomentVo> transform(Integer corpId, JSONArray allMomentArr) {
        List<WxMomentDto> allMomentDto = allMomentArr.toJavaList(WxMomentDto.class);
        ArrayList<MomentVo> list = new ArrayList<>();
        for (WxMomentDto dto : allMomentDto) {
            MomentVo entity = new MomentVo();
            BeanUtils.copyProperties(dto, entity);
            entity.setWxEmployeeId(dto.getCreator());
            transform1(corpId, dto, entity);
            list.add(entity);
        }
        return list;
    }

    /**
     * 根据momentId从朋友圈发表列表中获取合法的legalWxEmployeeIds
     * @param momentId
     * @return legalWxEmployeeIds
     */
    private ArrayList<String> getLegalWxEmployeeIds(String momentId) {
        String taskJson = WxApiUtils.getMomentTask(CorpContextHolder.getCorpId(), momentId);
        JSONArray tasks = JSONArray.parseArray(taskJson);
        ArrayList<String> legalWxEmployeeIds = new ArrayList<>();
        if (!tasks.isEmpty()) {
            for (int i = 0; i < tasks.size(); i++) {
                Integer publishStatus = (Integer) tasks.getJSONObject(i).get("publish_status");
                if (publishStatus.equals(1)) {
                    legalWxEmployeeIds.add(tasks.getJSONObject(i).get("userid").toString());
                }
            }
        }
        return legalWxEmployeeIds;
    }

    //此方法内调的企业微信API(WxApiUtils.getMomentComments)有问题，有时候json为null
    public InteractionVo interaction(String wxMomentId, String wxEmployeeId) {
        Integer corpId = AccountService.getCorpId();
        JSONObject json = JSONObject.parseObject(WxApiUtils.getMomentComments(corpId, wxMomentId, wxEmployeeId));
        JSONArray likeArr = json.getJSONArray("like_list");
        JSONArray commentArr = json.getJSONArray("comment_list");
        InteractionVo interactionVo = new InteractionVo(likeArr.size(), commentArr.size());
        return interactionVo;
    }

    void transform1(Integer corpId, WxMomentDto dto, MomentVo entity) {
        if (dto.getText() != null && dto.getText().getContent() != null) entity.setTextContent(dto.getText().getContent());
        if (dto.getImage() != null &&  dto.getImage().size() != 0) entity.setImageMediaId(JSONObject.toJSONString(dto.getImage()));
        if (dto.getVideo() != null && dto.getVideo().getMediaId() != null) entity.setVideoMediaId(dto.getVideo().getMediaId());
        if (dto.getVideo() != null && dto.getVideo().getThumbMediaId() != null) entity.setVideoThumbMediaId(dto.getVideo().getThumbMediaId());
        if (dto.getLink() != null && dto.getLink().getTitle() != null) entity.setLinkTitle(dto.getLink().getTitle());
        if (dto.getLink() != null && dto.getLink().getUrl() != null) entity.setLinkUrl(dto.getLink().getUrl());
        QueryWrapper<WorkEmployeeEntity> wrapper = new QueryWrapper<>();
        wrapper.select("name").eq("wx_user_id", dto.getCreator()).eq("corp_id", corpId);
        String name = workEmployeeService.getObj(wrapper, o -> o.toString());
        entity.setEmployeeName(name);
        LocalDateTime time = LocalDateTime.ofEpochSecond(dto.getCreate_time(), 0, ZoneOffset.ofHours(8));
        entity.setCreateTime(time.toLocalDate().toString());
    }


}
